package lv.solcraft.replication.server.scheduler;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

public class ScheduledExecutorJob implements StatefulJob {

    public static final String BEAN_NAME_PARAM = "BEAN_NAME";
    public static final String APPLICATION_CONTEXT_PARAM = "APPLICATION_CONTEXT";

    public void execute(JobExecutionContext jobContext) throws JobExecutionException {
        ApplicationContext applicationContext = (ApplicationContext) jobContext.getJobDetail().getJobDataMap().get(APPLICATION_CONTEXT_PARAM);
        Assert.notNull(applicationContext, "Application context is null in job detail ");
        String beanName = jobContext.getJobDetail().getJobDataMap().getString(BEAN_NAME_PARAM);
        Assert.hasText(beanName, "Bean name not found or empty in job detail ");
        Scheduled scheduled = (Scheduled) applicationContext.getBean(beanName);
        try {
            scheduled.execute();
        } catch (Exception e) {
            throw new JobExecutionException(e, false);
        }
    }
}
